package com.nobuyme.box.toy;


import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.nobuyme.box.R;
import com.nobuyme.box.account.Account;
import com.nobuyme.box.account.AccountManager;
import com.nobuyme.box.app.UrlCenter;
import com.nobuyme.box.common.http.MyHttpRequest;
import com.nobuyme.box.toy.manage.NeedReplaceActivity;
import com.nobuyme.box.toy.manage.OffGoodsActivity;
import com.nobuyme.box.toy.manage.PutGoodsActivity;
import com.nobuyme.box.util.StrokeTextView;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeGridFragment;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.framework.httprequest.responsecallbacks.ListDataRequestListener;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class ToyManageListFragment extends SwipeGridFragment {

    public static final int EMPTYCONTAINER = 0;
    public static final int PENDINGLEASE = 1;
    public static final int WAITRECYCLE = 2;
//    public static final int NEEDREPLACE = 3;
    public static final int POSITION = 10;
    public static final int LATTED_ID = 10;
    private int mPage = 0;
    private int status;
    private int putPosition;
    public ToyManageListFragment() {
        super(3);
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        Bundle bundle = getArguments();//从activity传过来的Bundle
        if(bundle!=null){
            status = bundle.getInt("status");
        }
        startLoading();
        clearDecorations();
        setPullToRefreshEnable(false);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

//    @Override
//    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long itemId) {
//        super.onItemClick(arg0, arg1, position, itemId);
//        ToyListFragment.TestBean data;
//        data = (ToyListFragment.TestBean) getData().get(position);
//        if (position == 0) {
//            //可上货
//            PutGoodsActivity.start(getActivity(),data);
//        }
//        if (position == 1) {
//            //未租借需替换
//            ReplaceGoodsActivity.start(getActivity());
//        }
//        if (position == 2) {
//            NeedReplaceActivity.start(getActivity());
//        }
//
//    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new ToyManageListAdapter(getActivity());
    }

    private ListDataRequestListener<ToyListFragment.TestBean> mResponceListener = new ListDataRequestListener<>(this, ToyListFragment.TestBean.class);

    @Override
    public void onStartLoading() {
        int id = AccountManager.getCurrentAccount().getId();
        if (mResponceListener.getResponseDataParser().hasMore()) {
            mPage++;
        }
        IHttpRequest request = new MyHttpRequest(getContext());
        UrlParams params = new UrlParams();
        params.put("ageRangeId", 0 + "");
        params.put("toyboxId", id + "");//toybox 机子对应的id
        params.put("pageNo", mPage+"");
        params.put("pageSize", 80+"");
        params.put("status", status+"");
        Log.e("status1",status+"");
        request.get(UrlCenter.GOODS_LIST, params, mResponceListener);
    }

    public class ToyManageListAdapter extends RecyclerViewBaseAdapter<ToyListFragment.TestBean> {


        public ToyManageListAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            return new ToyManageHolder(setAdapterViewItem(parent, R.layout.list_manage_item));
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder ItemHolder,final int position) {

           final ToyListFragment.TestBean testBean = getData().get(position);
            ToyManageHolder holder = (ToyManageHolder) ItemHolder;
            // 获取背景颜色，并且改变颜色
            holder.mRlManageColor.setBackgroundResource(R.drawable.manage_list_shape_green);
            holder.mStvManageNum.setTextColor(Color.parseColor("#F3D120"));
            holder.mTvManageNum.setText(testBean.getLattice_code());

            //状态：0 空箱   1、待租赁  2、等待回收  3、锁定（未租借需替换）
            if (testBean.getStatus() == EMPTYCONTAINER) {
                holder.mStvManageNum.setText("可上货");
                holder.mIvManageList.setImageResource(R.mipmap.emity_pic);
            } else if (testBean.getStatus() == PENDINGLEASE) {
                holder.mStvManageNum.setText("待租赁");
                Glide.with(getActivity()).load(testBean.getCover()).into(holder.mIvManageList);
            } else if (testBean.getStatus() == WAITRECYCLE) {
                holder.mStvManageNum.setText("需回收");
                Glide.with(getActivity()).load(testBean.getCover()).into(holder.mIvManageList);
            }
//            else if (testBean.getStatus() == NEEDREPLACE) {
//                holder.mStvManageNum.setText("未租借需替换");
//                Glide.with(getActivity()).load(testBean.getCover()).into(holder.mIvManageList);
//            }

            holder.mRlManageItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialog();
                }
                private void showDialog() {
                    final AlertDialogFragment alertDialogFrag = new AlertDialogFragment();
                    alertDialogFrag.setMessage(R.string.make_sure_to_open)
                       .setPositiveButton(R.string.make_sure, new View.OnClickListener() {
                           @Override
                           public void onClick(View v) {
                               //空箱  带上货
                               String openPosition = testBean.getLattice_code();
                               try {
                                   putPosition = Integer.parseInt(openPosition);
                               } catch (NumberFormatException e) {
                                   e.printStackTrace();
                               }
                               if(testBean.getStatus() == EMPTYCONTAINER){
                                //0表示空箱准备上货
                                   setOpenSuccess(testBean.getLattice_id(),1, testBean,0,putPosition);
                               }
                               //未租借需替换
                                  else if(testBean.getStatus() == PENDINGLEASE){
                                 setOpenSuccess(testBean.getLattice_id(),1, testBean,1,putPosition);
                               //需回收
                               }
                               else if(testBean.getStatus() == WAITRECYCLE){
                                   //0表示上货，1表示替换
                               setOpenSuccess(testBean.getLattice_id(), 1, testBean,2,putPosition);
                               }
                               alertDialogFrag.dismiss();
                           }
                       })
                            .setNegativeButton(R.string.put_goods_cencal, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    alertDialogFrag.dismiss();
                                }
                            })
                            .show(getFragmentManager());
                }
            });
        }

        //开柜
        private void setOpenSuccess(int lattice_id, int type, final ToyListFragment.TestBean testBean, final int type1,final int openPosition) {
            Account acc= AccountManager.getCurrentAccount();
            HttpRequest req = new HttpRequest(getContext());
            String urlAll =String.format(UrlCenter.BOX_OPEN,acc.getId(),lattice_id,type);
            req.put(urlAll, null, new DataRequestListener<Object>(Object.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }
                @Override
                public void onSuccess(Object o) {
                    super.onSuccess(o);
                    if(type1==0){
                        PutGoodsActivity.start(getActivity(),testBean,openPosition);
                        getActivity().finish();
                    }else if(type1==1){
                        OffGoodsActivity.start(getActivity(),testBean,openPosition);
                        getActivity().finish();
                    }else if(type1==2){
                        NeedReplaceActivity.start(getActivity(),testBean,openPosition);
                        getActivity().finish();
                    }

                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                }
            });

        }

        class ToyManageHolder extends RecyclerView.ViewHolder {
            @Bind(R.id.rl_manage_color)
            RelativeLayout mRlManageColor;
            @Bind(R.id.stv_manage_num)
            StrokeTextView mStvManageNum;
            @Bind(R.id.tv_manage_num)
            TextView mTvManageNum;
            @Bind(R.id.iv_manage_list)
            ImageView mIvManageList;
            @Bind(R.id.rl_manage_item)
            RelativeLayout mRlManageItem;

            public ToyManageHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }

    }

}
